import React, { useState, useRef, useMemo } from 'react';
import {
    Form,
    Input,
    Button,
    Picker,
    Radio,
    Toast
} from 'antd-mobile';

import { createArticleAPI, getArticleById, updateArticleAPI } from '@/apis/article'
import { useChannel } from '@/hooks/useChannel'
import { Link, useSearchParams } from 'react-router-dom'

import { LimitCount } from '@/components/LimitCount';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';


export default () => {
    // 获取频道列表
    const { channelList } = useChannel()
    // 将 channels 数据转换为 Picker 所需的格式
    const pickerData = useMemo(() => {
        return (channelList || []).map(channel => ({
            label: channel.name,
            value: channel.id,
        }));
    }, [channelList]); // 只有当 channelList 变化时才会重新计算
    const pickerMap = [pickerData]
    const [visible, setVisible] = useState(false)
    const [value, setValue] = useState('');

    // 切换图片封面类型
    const [imageType, setImageType] = useState(0)

    // 新增状态管理
    const [fileList, setFileList] = useState([]);

    const [loading, setLoading] = useState(false);

    const quillRef = useRef(null);

      // 获取实例
     const [form] = Form.useForm()

    // 回填数据
    const [searchParams] = useSearchParams()
    const articleId = searchParams.get('id')

    const onTypeChange = (e) => {
        setImageType(e)
        // console.log('imageType', imageType)
    }

    // 提交表单
    const onFinish = async (formValue) => {
    
        // 校验封面类型imageType是否和实际的图片列表imageList数量是相等的
        if (fileList.length !== imageType) return Toast.show('封面类型和图片数量不匹配')
        const { title, content, channel_id } = formValue
        // 1. 按照接口文档的格式处理收集到的表单数据
        const reqData = {
            title,
            content,
            cover: {
                type: imageType, // 封面模式
                // 这里的url处理逻辑只是在新增时候的逻辑
                // 编辑的时候需要做处理
                images: fileList.map(item => {
                    if (item.response) {
                        return item.response.data.url
                    } else {
                        return item.url
                    }
                }) // 图片列表
            },
            channel_id
        }
        reqData.channel_id=value[0]
        console.log('reqData', reqData)

        setLoading(true);
        try {
            if (articleId) {
            } else {
                createArticleAPI(reqData).then(res => {
                    // console.log('更新接口',res)
                    if (res.message === 'OK') {
                        Toast.show('提交成功')
                        // console.log('提交成功')
                    }
                    setLoading(false);
                }).catch(err => {
                    console.log(err)
                })
            }
        } catch (error) {
            setLoading(false);
            console.log(error)
        }finally {
        }
        
    }

    return (
        <>
            <Form
                layout="horizontal"
                form={form}
                onFinish={onFinish}
                footer={
                    <Button  loading={loading} loadingText='提交中' block type="submit" color="primary" size="large">
                        提交
                    </Button>
                }
            >
                <Form.Item
                    name="title"
                    label="标题"
                    rules={[{ required: true, message: '请输入文章标题' }]}
                >
                    <Input placeholder="请输入文章标题" />
                </Form.Item>

                <Form.Item
                    required
                    // name="channel_id"
                    label='频道'
                    onClick={() => {
                        setVisible(true)
                    }}
                >
                    <Picker
                        columns={pickerMap}
                        visible={visible}
                        onClose={() => {
                            setVisible(false)
                        }}
                        value={value}
                        onConfirm={v => {
                            // console.log(v)
                            setValue(v)
                        }}
                    >
                    </Picker>
                    <span>{channelList.find(item => item.id === value[0])?.name || '请选择'}</span>
                </Form.Item>

                <Form.Item label='封面' required>
                    <Radio.Group onChange={onTypeChange}>
                        <Radio value={1}>单图</Radio>
                        <Radio value={3}>三图</Radio>
                        <Radio value={0}>无图</Radio>
                    </Radio.Group>
                </Form.Item>

                {imageType != 0 &&
                    <LimitCount
                        maxCount={imageType}
                        onFileListChange={setFileList}
                    />
                }

                <Form.Item
                    label="内容"
                    name="content"
                    rules={[{ required: true, message: '请输入文章内容' }]}
                >
                    {/* 富文本编辑器 */}
                    <ReactQuill
                        ref={quillRef}
                        className="publish-quill"
                        theme="snow"
                        placeholder="请输入文章内容"
                    />
                </Form.Item>


            </Form>
        </>
    );
};
